package com.yjymm.edu.interceptor;

import com.yjymm.edu.common.LoginUserContext;
import com.yjymm.edu.model.common.CommonResult;
import com.yjymm.edu.model.common.CommonResultEnum;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yjymm
 * @date 2021-01-13 23:14
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (LoginUserContext.getUser() != null) {
            // 验证成功
            return true;
        }
        CommonResult build = CommonResult.builder()
                .code(CommonResultEnum.NO_LOGIN.getCode())
                .message(CommonResultEnum.NO_LOGIN.getMessage())
                .build();

        response.getWriter().write(LoginUserContext.getObjectMapper().writeValueAsString(build));
        return false;
    }
}
